<?php

namespace app\api\controller;

use app\api\model\User as UserModel;
use app\common\library\wechat\WxBase as WxBase;
use app\common\model\Wxapp as WxappModel;

/**
 * 
 * Class User
 * @package app\api
 */
class Phone extends Controller
{
    /**
     * 手机号解析
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function index($phone_code)
    {
        // 请求手机号和access_token
        if (!empty($phone_code)) {
            $rs = $this->getWxPhoneNumber($phone_code);
            if ($rs['phone']['errmsg'] == "ok") {
                $phone = $rs['phone']['phone_info']['phoneNumber'];
                return $this->renderSuccess(compact('phone'));
            }else{
                return $this->renderError('没有获取到手机号');
            }
        }
    }
    public function getWxToken()
    {
        $WxappModel = new WxappModel();
        $wxapp = $WxappModel->getWxappCache();
        $WxBase = new WxBase($wxapp['app_id'], $wxapp['app_secret']);
        return $getAccessToken = $WxBase->getAccessToken();
    }
    public function getWxPhoneNumber($code)
    {
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $this->getWxToken();
        $data = json_encode(["code" => $code]);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);        // 发送post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 传入post参数
        $res = curl_exec($ch);
        curl_close($ch);
        $arr = [
            'phone' => json_decode($res, true)
        ];
        return $arr;
    }
}
